//
//  CreateJobService.swift
//  GreenDeal
//
//  Created by Moennig Q on 1/3/2023.
//

import UIKit
import HandyJSON
import SwiftyJSON
import Alamofire
class CreateJobService: BaseService {
    //MARK: -获取当前installer所在的company
    func getCompanyList(){
        let urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetCompanyListAPI)
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            guard let data = obj else{
                return
            }
            //data list
            let json = JSON(data)
            if let list = JSONDeserializer<CompanyModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<CompanyModel>{
                self.returnBlock(list, nil)
            }
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -获取某个company下的Agent list
    func getAgentList(_ companyId: Int){
        let urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetAgentListAPI)  + "\(companyId)"
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            guard let data = obj else{
                return
            }
            //data list
            let json = JSON(data)
            if let list = JSONDeserializer<AgentModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<AgentModel>{
                self.returnBlock(list, nil)
            }
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -获取某个时间段内的各个job 的status list
    func getJobStatusList(_ beginDate: Date, endDate: Date){
        var realBeginDate = beginDate
        let minDate = DateUtil().getServeralYearOfToday(date: Date(), year: -1, day: 1)//最小日期是一年前
        let minDateInternal = minDate.timeIntervalSince1970
        let beginInternal = beginDate.timeIntervalSince1970
        if minDateInternal > beginInternal{//最小日期大于开始日期，表示开始日期比最小日期还要往前，将最小日期设置为开始日期
            realBeginDate = minDate
        }
        let beginDateStr = DateUtil().getDatetimeStr(realBeginDate,format: "yyyy-MM-dd")
        let endDateStr = DateUtil().getDatetimeStr(endDate,format: "yyyy-MM-dd")
        let urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetJobsStatusBetweenDate) + "?begin_date=" + beginDateStr + "&end_date=" + endDateStr
        
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            guard let data = obj else{
                return
            }
            //data list
            let json = JSON(data)
            if let list = JSONDeserializer<CreateJobStatusModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<CreateJobStatusModel>{
                self.returnBlock(list, nil)
            }
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest(cacheFlag: false)
    }
    //MARK: -获取当前创建job的rec quantity
    func getStcsByPanels(postCode: String, systemSize: Double, installDate: String){
        let urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetStcsByTotalPanelWatts) + "?post_code=" + postCode + "&system_size=\(systemSize)" + "&install_date=" + installDate
        
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            guard let data = obj else{
                return
            }
            self.returnBlock(data, nil)
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -创建Job前或增加panel，，如果可以开启SPV，要提示用户是否开启SPV
    func validSPVCheckBeforeUpdatePanel(panels: [InstallationDetailSystemDetailForPanelModel], companyID: Int){
        let brandStr: String = panels.map { $0.brand }.joined(separator: ",")
        var urlString : String = APIConfig.getRequestAPIForV2(APIConfig.ValidSPVCheckBeforeUpdatePanelAPI) + "?brands=" + brandStr + "&company_id=\(companyID)"
        if let data = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
            urlString = data
        }
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            guard let data = obj else{
                return
            }
            self.returnBlock(data, nil)
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: -创建Job
    func createJob(_ viewModel: CreateJobViewModel){
        //install address
        let sameAsPostalAddress = viewModel.installationAddressViewModel.sameAsPostalAddress
        var installAddressModel = [String: Any]()
        installAddressModel["property_type"] = viewModel.propertyOwner.property_type.rawValue
        installAddressModel["nmi"] = viewModel.systemDetail.nmi
        installAddressModel["unit_type"] = viewModel.installationAddressViewModel.installAddress.unit_type
        installAddressModel["unit_number"] = viewModel.installationAddressViewModel.installAddress.unit_number
        installAddressModel["street_number"] = viewModel.installationAddressViewModel.installAddress.street_number
        //处理street name中的-，用空格替换，以为提交是Rec不允许
        let realStreetName: String = viewModel.installationAddressViewModel.installAddress.street_name.replacingOccurrences(of: "-", with: " ")
        installAddressModel["street_name"] = realStreetName
        installAddressModel["street_type"] = viewModel.installationAddressViewModel.installAddress.street_type
        installAddressModel["post_code"] = viewModel.installationAddressViewModel.installAddress.post_code
        installAddressModel["suburb"] = viewModel.installationAddressViewModel.installAddress.suburb
        installAddressModel["state"] = viewModel.installationAddressViewModel.installAddress.state
        installAddressModel["installed_optimiser"] = (viewModel.systemDetail.installed_optimiser ? "true": "false")
        installAddressModel["geoscape_address_id"] = viewModel.installationAddressViewModel.installAddress.address_id//可以为空
        installAddressModel["address_text"] = viewModel.installationAddressViewModel.installAddress.full_address
        installAddressModel["same_as_postal"] = (sameAsPostalAddress ? "true" : "false")//默认true
        if viewModel.installationAddressViewModel.addSpecialAddressFlag {
            installAddressModel["special_address"] = viewModel.installationAddressViewModel.specialAddress
        }
        //
        installAddressModel["story"] = viewModel.siteAttributesViewModel.story.rawValue//"Single story"//或者：Multi story，
        installAddressModel["roof"] = viewModel.siteAttributesViewModel.roof.rawValue
        installAddressModel["panel_type"] = viewModel.siteAttributesViewModel.panel_type.rawValue
        installAddressModel["phase"] = viewModel.siteAttributesViewModel.phase.rawValue
        //
        installAddressModel["grid_connection_application_ref_no"] = viewModel.systemDetail.gridConnectionApplicationRefNo

        //owner info
        var ownerInfoModel = [String: Any]()
        ownerInfoModel["owner_type"] = viewModel.propertyOwner.owner_type.rawValue
        //email , phone 共用
        ownerInfoModel["phone"] = viewModel.propertyOwner.mobile
        ownerInfoModel["email"] = viewModel.propertyOwner.email
        
        //individual
        if viewModel.propertyOwner.owner_type == .individual {//individual
            ownerInfoModel["first_name"] = viewModel.propertyOwner.first_name
            ownerInfoModel["last_name"] = viewModel.propertyOwner.surname
            if viewModel.propertyOwner.co_owner_optional {
                ownerInfoModel["co_owner_relation_ship"] = viewModel.propertyOwner.co_owner_relation_ship
                ownerInfoModel["co_owner_last_name"] = viewModel.propertyOwner.co_owner_surname
                ownerInfoModel["co_owner_first_name"] = viewModel.propertyOwner.co_owner_first_name
            }
        }else{//commertial
            ownerInfoModel["home_owner_abn"] = viewModel.propertyOwner.home_owner_abn
            ownerInfoModel["owner_type_name"] = viewModel.propertyOwner.company_name
            ownerInfoModel["owner_representative_name"] = viewModel.propertyOwner.owner_representative_name
            ownerInfoModel["owner_representative_position"] = viewModel.propertyOwner.owner_representative_position
            ownerInfoModel["price_to_the_home_owner"] = viewModel.propertyOwner.price_to_the_home_owner
        }
        //postal address
        if sameAsPostalAddress {
            ownerInfoModel["address_type"] = AddressType.physical.rawValue
            ownerInfoModel["address_text"] = viewModel.installationAddressViewModel.installAddress.full_address
            ownerInfoModel["unit_type"] = viewModel.installationAddressViewModel.installAddress.unit_type
            ownerInfoModel["unit_number"] = viewModel.installationAddressViewModel.installAddress.unit_number
            ownerInfoModel["street_number"] = viewModel.installationAddressViewModel.installAddress.street_number
            //处理street name中的-，用空格替换，以为提交是Rec不允许
            let realStreetName: String = viewModel.installationAddressViewModel.installAddress.street_name.replacingOccurrences(of: "-", with: " ")
            ownerInfoModel["street_name"] = realStreetName
            ownerInfoModel["street_type"] = viewModel.installationAddressViewModel.installAddress.street_type
            ownerInfoModel["post_code"] = viewModel.installationAddressViewModel.installAddress.post_code
            ownerInfoModel["suburb"] = viewModel.installationAddressViewModel.installAddress.suburb
            ownerInfoModel["state"] = viewModel.installationAddressViewModel.installAddress.state
        }else{
            ownerInfoModel["address_type"] = viewModel.installationAddressViewModel.postalAddress.address_type.rawValue
            if viewModel.installationAddressViewModel.postalAddress.address_type == .physical{
                ownerInfoModel["address_text"] = viewModel.installationAddressViewModel.postalAddress.physicalAddress.full_address
                ownerInfoModel["unit_type"] = viewModel.installationAddressViewModel.postalAddress.physicalAddress.unit_type
                ownerInfoModel["unit_number"] = viewModel.installationAddressViewModel.postalAddress.physicalAddress.unit_number
                ownerInfoModel["street_number"] = viewModel.installationAddressViewModel.postalAddress.physicalAddress.street_number
                //处理street name中的-，用空格替换，以为提交是Rec不允许
                let realStreetName: String = viewModel.installationAddressViewModel.postalAddress.physicalAddress.street_name.replacingOccurrences(of: "-", with: " ")
                ownerInfoModel["street_name"] = realStreetName
                ownerInfoModel["street_type"] = viewModel.installationAddressViewModel.postalAddress.physicalAddress.street_type
                ownerInfoModel["post_code"] = viewModel.installationAddressViewModel.postalAddress.physicalAddress.post_code
                ownerInfoModel["suburb"] = viewModel.installationAddressViewModel.postalAddress.physicalAddress.suburb
                ownerInfoModel["state"] = viewModel.installationAddressViewModel.postalAddress.physicalAddress.state
            }else{//PO box
                ownerInfoModel["delivery_type"] = viewModel.installationAddressViewModel.postalAddress.delivery_type
                ownerInfoModel["delivery_number"] = viewModel.installationAddressViewModel.postalAddress.delivery_number
                ownerInfoModel["post_code"] = viewModel.installationAddressViewModel.postalAddress.post_code
                ownerInfoModel["suburb"] = viewModel.installationAddressViewModel.postalAddress.suburb
                ownerInfoModel["state"] = viewModel.installationAddressViewModel.postalAddress.state
                ownerInfoModel["address_text"] = viewModel.installationAddressViewModel.postalAddress.po_box_full_address
            }
        }
        
        //4.system info
        var systemInfoModel = [String: Any]()
        systemInfoModel["install_on_building"] = viewModel.siteAttributesViewModel.install_on_building.rawValue
        systemInfoModel["installation_type"] = viewModel.systemDetail.installation_type.rawValue
        systemInfoModel["additional_capacity_details"] = viewModel.systemDetail.additional_capacity_details
        systemInfoModel["install_date"] = DateUtil().getDatetimeStr(viewModel.installDate, format: "yyyy-MM-dd")
        systemInfoModel["connected_type"] = viewModel.systemDetail.connected_type.rawValue
        systemInfoModel["is_battery"] = viewModel.systemDetail.is_battery ? "true": "false"
        systemInfoModel["installer_job_site_instruction"] = viewModel.installerDetail.installer_job_site_instruction
        //panel list
        var panels = [[String: Any]]()
        for data in viewModel.systemDetail.panels{
            var newModel = [String: Any]()
            newModel["brand_id"] = "\(data.panel_brand_id)"
            newModel["watts_per"] = "\(data.watts_per_panel)"
            newModel["qty"] = "\(data.number_panels)"
            panels.append(newModel)
        }
        systemInfoModel["pvd_system_panels"] = panels
        //inverter list
        var inverters = [[String: Any]]()
        for data in viewModel.systemDetail.inverters{
            var newModel = [String: Any]()
            newModel["brand_id"] = "\(data.inverter_brand_id)"
            newModel["qty"] = "\(data.number_inverters)"
            inverters.append(newModel)
        }
        systemInfoModel["pvd_system_inverters"] = inverters
        //battery list
        var batteries = [[String: Any]]()
        for data in viewModel.systemDetail.batteries{
            var newModel = [String: Any]()
            newModel["brand_id"] = "\(data.battery_storage_id)"
            newModel["qty"] = "\(data.number_batteries)"
            newModel["battery_system_part_of_an_aggregated_control"] = (data.battery_system_part_of_an_aggregated_control ? "true" : "false")
            newModel["changed_the_default_battery_manufacturer_setting"] = (data.changed_the_default_battery_manufacturer_setting ? "true" : "false")
            batteries.append(newModel)
        }
        systemInfoModel["pvd_system_batteries"] = batteries
        
        //5.installer info
        var installerInfoModel = [String: Any]()
        installerInfoModel["installer_id"] = viewModel.installerDetail.installerID
        installerInfoModel["designer_id"] = viewModel.installerDetail.designerID
        installerInfoModel["electrician_id"] = viewModel.installerDetail.electricianID
        //
        let params: Parameters = ["company_id": viewModel.summaryViewModel.company_id,
                                  "pick_up_required": viewModel.installerDetail.pickupRequired ? "true": "false",
                                  "delivery_address_id": viewModel.installerDetail.delivery_address_id,
                                  "pick_up_reference":  viewModel.installerDetail.pickupReference,
                                  "spv_check": viewModel.summaryViewModel.spv_check ,
                                  "agent_id": viewModel.summaryViewModel.agent_id ,
                                  "trade_mode": viewModel.summaryViewModel.trade_mode.rawValue ,
                                  "customer_po": viewModel.summaryViewModel.customer_po ,
                                  "pvd_install_address": installAddressModel,
                                  "pvd_owner_address": ownerInfoModel,
                                  "pvd_system": systemInfoModel ,
                                  "pvd_installer": installerInfoModel,
                                  "gst": "\(viewModel.propertyOwner.gst)"]
        //获取Post字符串
        Tool().printPostJSONString(params)
        //
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.CreateJobAPI), method: .post, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj, _) -> Void in
            guard let data = obj else {
                self.errorBlock?("", "request data faild")
                return
            }
            let json = JSON(data)
            let modeStr = json.rawString()
            
            if let model = JSONDeserializer<PVDDetailModel>.deserializeFrom(json: modeStr){
                self.returnBlock(model,nil)
            }else{
                self.errorBlock?("","CreateJobAPI data convert to PVDDetailModel faild")
            }
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
}
